package com.pan.server.impl;

import com.pan.hendle.req.RequestHandle;
import com.pan.hendle.resp.ResponseHandle;
import com.pan.server.Server;
import com.pan.server.config.ServerConfig;
import com.pan.server.config.SocketPoolConfig;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public abstract class BasicServer implements Server, ServerConfig, SocketPoolConfig {

    private ServerSocket serverSocket;
    protected ServerSocket getServerSocket() {
        return serverSocket;
    }

    private RequestHandle requestHandle;
    protected RequestHandle getRequestHandle() {
        return requestHandle;
    }

    private ResponseHandle responseHandle;

    protected ResponseHandle getResponseHandle() {
        return responseHandle;
    }

    private ThreadPoolExecutor socketPool;
    protected ThreadPoolExecutor getSocketPool() {
        return socketPool;
    }
    public BasicServer(){
        int port = this.getPort();
        int backlog = this.getBacklog();
        try {
            serverSocket = new ServerSocket(port,backlog,null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        int corePoolSize,maxPoolSize,keepAlive,queueSize;
        corePoolSize = this.getAliveTime();
        maxPoolSize = this.getPoolMaxSize();
        keepAlive = this.getAliveTime();
        queueSize = this.getBlockQueueSize();
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(queueSize);
        socketPool = new ThreadPoolExecutor(corePoolSize,maxPoolSize,keepAlive,
                TimeUnit.SECONDS,blockingQueue);

    }

    public void setRequestHandle(RequestHandle requestHandle) {
        this.requestHandle = requestHandle;
    }

    public void setResponseHandle(ResponseHandle responseHandle) {
        this.responseHandle = responseHandle;
    }
}
